import L from 'leaflet';
import 'leaflet-draw';
// import { SuperMap } from '@supermap/iclient-leaflet'
import '@/libs/leaflet/iclient-leaflet'
import '@/libs/leaflet-draw/local.cn'
import 'leaflet/dist/leaflet.css';
// import '../libs/iclient-plot-leaflet/iclient-plot-leaflet.min'
import '@/libs/leaflet/iclient-leaflet.css';
import '@/libs/iclient-plot-leaflet/iclient-plot-leaflet.css';
import 'leaflet-draw/dist/leaflet.draw.css';
import iconBlue from '@/assets/images/icon-gps-blue.png'
import iconGreen from '@/assets/images/icon-gps-green.png'
import iconOrange from '@/assets/images/icon-gps-orange.png'
import iconQrcode from '@/assets/images/icon-qrcode.png'

if (L === undefined) {
    throw new Error('L is undefined')
}

var map, layer, options, prjCoordSys, epsgcode, url = "http://23.99.215.161:8195/portalproxy/v1cje8d5/iserver/services/map-mbtiles-yzqdzdt/rest/maps/渝中区电子地图18", isSingleImage = false;
var lon = 0, lat = 0, zoomlevel = 2, initZoomToScale;
var queryString = "";
let globalConfig = {}; // globalConfig
var originResult = { "viewBounds": { "top": 3462406.2887437195, "left": 1.1839407748109672E7, "bottom": 3423270.5302617196, "leftBottom": { "x": 1.1839407748109672E7, "y": 3423270.5302617196 }, "right": 1.1878543506591674E7, "rightTop": { "x": 1.1878543506591674E7, "y": 3462406.2887437195 } }, "viewer": { "leftTop": { "x": 0, "y": 0 }, "top": 0, "left": 0, "bottom": 256, "rightBottom": { "x": 256, "y": 256 }, "width": 256, "right": 256, "height": 256 }, "distanceUnit": null, "minVisibleTextSize": 0, "coordUnit": "METER", "scale": 1.730727497321572E-6, "description": "", "paintBackground": false, "maxVisibleTextSize": 0, "maxVisibleVertex": 0, "clipRegionEnabled": false, "antialias": false, "textOrientationFixed": false, "angle": 0, "prjCoordSys": { "distanceUnit": "METER", "projectionParam": { "centralParallel": 0, "firstPointLongitude": 0, "rectifiedAngle": 0, "scaleFactor": 1, "falseNorthing": 0, "centralMeridian": 0, "secondStandardParallel": 0, "secondPointLongitude": 0, "azimuth": 0, "falseEasting": 0, "firstStandardParallel": 0 }, "epsgCode": 3857, "coordUnit": "METER", "name": "User Define", "projection": { "name": "SPHERE_MERCATOR", "type": "PRJ_SPHERE_MERCATOR" }, "type": "PCS_WGS_1984_WEB_MERCATOR", "coordSystem": { "datum": { "name": "D_WGS_1984", "type": "DATUM_WGS_1984", "spheroid": { "flatten": 0.0033528106647474805, "name": "WGS_1984", "axis": 6378137, "type": "SPHEROID_WGS_1984" } }, "unit": "DEGREE", "spatialRefType": "SPATIALREF_EARTH_LONGITUDE_LATITUDE", "name": "GCS_WGS_1984", "type": "GCS_WGS_1984", "primeMeridian": { "longitudeValue": 0, "name": "Greenwich", "type": "PRIMEMERIDIAN_GREENWICH" } } }, "minScale": 0, "markerAngleFixed": false, "overlapDisplayedOptions": null, "visibleScales": [1.730727497321572E-6, 3.461454994643144E-6, 6.922909989286288E-6, 1.3845819978572576E-5, 2.769163995714515E-5, 5.53832799142903E-5, 1.107665598285806E-4, 2.215331196571612E-4, 4.430662393143224E-4], "dpi": 96, "visibleScalesEnabled": true, "customEntireBoundsEnabled": false, "clipRegion": null, "maxScale": 0, "customParams": "", "center": { "x": 1.1858975627350673E7, "y": 3442838.4095027195 }, "dynamicPrjCoordSyses": [{ "distanceUnit": "METER", "projectionParam": { "centralParallel": 0, "firstPointLongitude": 0, "rectifiedAngle": 0, "scaleFactor": 1, "falseNorthing": 0, "centralMeridian": 0, "secondStandardParallel": 0, "secondPointLongitude": 0, "azimuth": 0, "falseEasting": 0, "firstStandardParallel": 0 }, "epsgCode": 3857, "coordUnit": "METER", "name": "User Define", "projection": { "name": "SPHERE_MERCATOR", "type": "PRJ_SPHERE_MERCATOR" }, "type": "PCS_WGS_1984_WEB_MERCATOR", "coordSystem": { "datum": { "name": "D_WGS_1984", "type": "DATUM_WGS_1984", "spheroid": { "flatten": 0.0033528106647474805, "name": "WGS_1984", "axis": 6378137, "type": "SPHEROID_WGS_1984" } }, "unit": "DEGREE", "spatialRefType": "SPATIALREF_EARTH_LONGITUDE_LATITUDE", "name": "GCS_WGS_1984", "type": "GCS_WGS_1984", "primeMeridian": { "longitudeValue": 0, "name": "Greenwich", "type": "PRIMEMERIDIAN_GREENWICH" } } }], "colorMode": null, "textAngleFixed": false, "overlapDisplayed": false, "userToken": { "userID": "" }, "cacheEnabled": true, "dynamicProjection": false, "autoAvoidEffectEnabled": true, "customEntireBounds": null, "name": "渝中区电子地图18", "bounds": { "top": 3468865.2176888734, "left": 1.1806998448095882E7, "bottom": 3416811.6013165656, "leftBottom": { "x": 1.1806998448095882E7, "y": 3416811.6013165656 }, "right": 1.1910952806605464E7, "rightTop": { "x": 1.1910952806605464E7, "y": 3468865.2176888734 } }, "backgroundStyle": { "fillGradientOffsetRatioX": 0, "markerSize": 0, "fillForeColor": { "red": 255, "green": 0, "blue": 0, "alpha": 255 }, "fillGradientOffsetRatioY": 0, "markerWidth": 0, "markerAngle": 0, "fillSymbolID": 0, "lineColor": { "red": 0, "green": 0, "blue": 0, "alpha": 255 }, "markerSymbolID": 0, "lineWidth": 0.01, "markerHeight": 0, "fillOpaqueRate": 100, "fillBackOpaque": false, "fillBackColor": { "red": 255, "green": 255, "blue": 255, "alpha": 255 }, "fillGradientMode": "NONE", "lineSymbolID": 0, "fillGradientAngle": 0 } };
const key = 'S81p3M1Mv3Xz8Ln48gVkbT43';
const searchOptions = {
    cityConfig: ["重庆市"],
    pageSize: 20,
    onEachFeature: function (feature, el) {
        el.on('searchlayersucceeded', () => {
        })
    }
}
// create custom popup
L.CustomPopup = L.Popup.extend({
    _initLayout: function () {
        var prefix = 'leaflet-popup',
            container = this._container = L.DomUtil.create('div',
                prefix + ' ' + (this.options.className || '') +
                ' leaflet-zoom-animated');

        var wrapper = container;
        this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);

        L.DomEvent
            .disableClickPropagation(wrapper)
            .disableScrollPropagation(this._contentNode)
            .on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
    },
});
// add bindCustomPopup
L.Layer.include({

    // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
    // Binds a popup to the layer with the passed `content` and sets up the
    // neccessary event listeners. If a `Function` is passed it will receive
    // the layer as the first argument and should return a `String` or `HTMLElement`.
    bindCustomPopup: function (content, options) {

        if (content instanceof L.Popup) {
            L.setOptions(content, options);
            this._popup = content;
            content._source = this;
        } else {
            if (!this._popup || options) {
                this._popup = new L.CustomPopup(options, this);
            }
            this._popup.setContent(content);
        }

        if (!this._popupHandlersAdded) {
            this.on({
                click: this._openPopup,
                remove: this.closePopup,
                move: this._movePopup,
                // mouseover: this._openPopup,
            });
            this._popupHandlersAdded = true;
        }

        return this;
    }
});

// 渝中区中心点
// lat: 29.55895663434965
// lng: 106.55373573275868
// L.supermap.SecurityManager.registerKey(url, key);

//创建ICON构造函数，相当于继承于ICON，可以重新设置属性
var LeafIcon = L.Icon.extend({
    options: {
        shadowUrl: '', //阴影地址
        iconSize: [20, 20],  //图标宽高
    }

});

//创建多个icon
let blueIcon = new LeafIcon({
    iconUrl: iconBlue
});
let greenIcon = new LeafIcon({
    iconUrl: iconGreen
});
let orangeIcon = new LeafIcon({
    iconUrl: iconOrange
});

// 中继服务发送的请求，queryString字段是类似“token=&isSingleImage=true"这种情况，和普通请求做一下兼容处理
var parms = queryString.split("&");
for (var i = 0; i < parms.length; i++) {
    if (parms[i] == "isSingleImage=true") {
        isSingleImage = true;
        break;
    }
}

function init(config) {
    setPrjCoordSys(); // 初始化动态投影参数
    L.supermap.SecurityManager.registerKey(url, key);
    loadMap(config);
}

function initedLayer() {
    map.addLayer(layer);
    map.setView(L.latLng(lat, lon), zoomlevel);
    map.on('move', showScale);
    showScale();
    showCoords();
}

function loadMap(config) {
    var visableResolution = [152.8740565703125, 76.43702828515625, 38.21851414257812, 19.10925707128906, 9.55462853564453, 4.777314267822265, 2.3886571339111327, 1.1943285669555663, 0.5971642834777832];
    var mapcrs = L.CRS.EPSG3857;
    options = {};
    // 初始化时修改成22级，和计算scales数组时保持一致
    options.maxZoom = 22;
    options.minZoom = 2;
    var maxZoom = 22;
    var zoom = 4;
    if (originResult.overlapDisplayed) {
        options.overlapDisplayed = originResult.overlapDisplayed;
    }
    var envelope;

    if (originResult.prjCoordSys) {
        var resolution;
        if (originResult.prjCoordSys.coordUnit) {
            resolution = scaleToResolution(originResult.scale, originResult.dpi, originResult.prjCoordSys.coordUnit);
        }
        if (visableResolution.length == 0) {
            envelope = getProjectionExtent();
            if (!envelope) {
                envelope = originResult.bounds;
            }
            visableResolution = getStyleResolutions(envelope);
            var scales = getScales(envelope, originResult.prjCoordSys.coordUnit);
            if (originResult.scale) {
                var temp;
                for (var j = 0; j < scales.length; j++) {
                    if (j == 0) {
                        temp = Math.abs(originResult.scale - scales[j]);
                    }
                    if (temp > Math.abs(originResult.scale - scales[j])) {
                        temp = Math.abs(originResult.scale - scales[j]);
                        zoom = j;
                    }
                }
            }
        } else {
            if (resolution) {
                var temp;
                for (var j = 0; j < visableResolution.length; j++) {
                    if (j == 0) {
                        temp = Math.abs(resolution - visableResolution[j]);
                    }
                    if (temp > Math.abs(resolution - visableResolution[j])) {
                        temp = Math.abs(resolution - visableResolution[j]);
                        zoom = j;
                    }
                }
            }
        }
        if (isSingleImage) {

            if (epsgcode && originResult.prjCoordSys.type != "PCS_NON_EARTH") {//有设置动态投影而且不是平面坐标的地图
                if (epsgcode == "4326") {
                    options.projection = 4326;
                    if (visableResolution.length > 0) {
                        mapcrs = L.Proj.CRS("EPSG:4326", {
                            resolutions: visableResolution
                        });
                    } else {
                        mapcrs = L.Proj.EPSG4326;
                    }
                } else if (epsgcode == "3857") {
                    options.projection = 3857;
                    if (visableResolution.length > 0) {
                        mapcrs = L.Proj.CRS("EPSG:3857", {
                            resolutions: visableResolution
                        });
                    } else {
                        mapcrs = L.Proj.EPSG3857;
                    }
                }
            } else {//没有设置动态投影
                if (originResult.prjCoordSys.epsgCode == "4326" || originResult.prjCoordSys.type == "PCS_EARTH_LONGITUDE_LATITUDE") {
                    if (visableResolution.length > 0) {
                        mapcrs = L.Proj.CRS("EPSG:4326", {
                            resolutions: visableResolution
                        });
                    } else {
                        mapcrs = L.Proj.EPSG4326;
                    }
                } else if (originResult.prjCoordSys.type == "PCS_NON_EARTH") {
                    mapcrs = L.CRS.NonEarthCRS({
                        bounds: L.bounds([originResult.bounds.left, originResult.bounds.bottom], [originResult.bounds.right, originResult.bounds.top]),
                        origin: L.point(originResult.bounds.left, originResult.bounds.top)
                    });
                } else if (originResult.prjCoordSys.epsgCode == "3857") {
                    if (visableResolution.length > 0) {
                        mapcrs = L.Proj.CRS("EPSG:3857", {
                            resolutions: visableResolution
                        });
                    } else {
                        mapcrs = L.Proj.EPSG3857;
                    }
                } else {
                    if (visableResolution.length > 0) {
                        mapcrs = L.CRS.NonEarthCRS({
                            bounds: L.bounds([originResult.bounds.left, originResult.bounds.bottom], [originResult.bounds.right, originResult.bounds.top]),
                            resolutions: visableResolution,
                            origin: L.point(originResult.bounds.left, originResult.bounds.top)
                        });
                    } else {
                        mapcrs = L.CRS.NonEarthCRS({
                            bounds: L.bounds([originResult.bounds.left, originResult.bounds.bottom], [originResult.bounds.right, originResult.bounds.top]),
                            origin: L.point(originResult.bounds.left, originResult.bounds.top)
                        });
                    }
                }
            }

        } else {
            if (epsgcode && originResult.prjCoordSys.type != "PCS_NON_EARTH") {//有设置动态投影而且不是平面坐标的地图
                if (epsgcode == "4326") {
                    options.projection = 4326;
                    if (visableResolution.length > 0) {
                        mapcrs = getCRS("EPSG:4326", originResult.bounds, visableResolution);
                    } else {
                        mapcrs = getCRS("EPSG:4326", originResult.bounds);
                    }
                } else if (epsgcode == "3857") {
                    options.projection = 3857;
                    if (visableResolution.length > 0) {
                        mapcrs = getCRS("EPSG:3857", originResult.bounds, visableResolution);
                    } else {
                        mapcrs = getCRS("EPSG:3857", originResult.bounds);
                    }
                }
            } else {//没有设置动态投影
                if (originResult.prjCoordSys.epsgCode == "4326" || originResult.prjCoordSys.type == "PCS_EARTH_LONGITUDE_LATITUDE") {
                    lon = (originResult.bounds.left + originResult.bounds.right) / 2;
                    lat = (originResult.bounds.bottom + originResult.bounds.top) / 2;
                    var epsgStr = "EPSG:4326";
                    if (visableResolution.length > 0) {
                        mapcrs = getCRS(epsgStr, originResult.bounds, visableResolution);
                    } else {
                        mapcrs = getCRS(epsgStr, originResult.bounds);
                    }
                } else if (originResult.prjCoordSys.type == "PCS_NON_EARTH") {
                    mapcrs = L.CRS.NonEarthCRS({
                        bounds: L.bounds([originResult.bounds.left, originResult.bounds.bottom], [originResult.bounds.right, originResult.bounds.top]),
                        origin: L.point(originResult.bounds.left, originResult.bounds.top)
                    });
                } else if (originResult.prjCoordSys.epsgCode == "3857") {
                    if (visableResolution.length > 0) {
                        mapcrs = getCRS("EPSG:3857", originResult.bounds, visableResolution);
                    } else {
                        mapcrs = getCRS("EPSG:3857", originResult.bounds);
                    }
                } else {
                    if (visableResolution.length > 0) {
                        mapcrs = L.CRS.NonEarthCRS({
                            bounds: L.bounds([originResult.bounds.left, originResult.bounds.bottom], [originResult.bounds.right, originResult.bounds.top]),
                            resolutions: visableResolution,
                            origin: L.point(originResult.bounds.left, originResult.bounds.top)
                        });
                    } else {
                        mapcrs = L.CRS.NonEarthCRS({
                            bounds: L.bounds([originResult.bounds.left, originResult.bounds.bottom], [originResult.bounds.right, originResult.bounds.top]),
                            origin: L.point(originResult.bounds.left, originResult.bounds.top)
                        });
                    }
                }
            }
        }
    }

    if (visableResolution.length > 0) {
        maxZoom = visableResolution.length - 1;
        options.maxZoom = visableResolution.length - 1;
    }


    map = L.map(config.elId || 'map', {
        //crs: L.CRS.EPSG3857
        center: [29.55895663434965,106.55373573275868],
        maxZoom: maxZoom,
        zoom: zoom,
        crs: mapcrs,
    });

    var layerUrl = url;
    if (isSingleImage) {
        layer = L.supermap.imageMapLayer(layerUrl, options);
    } else {
        layer = L.supermap.tiledMapLayer(layerUrl, options);
    }
    layer.addTo(map);
    // 增加搜索服务
    if (config.search) {
        addSearch(map, config.search);
    }
    // 地图创建事件
    if (config.ready) {
        config.ready(map)
    }
}
function addSearch(map, searchConfig) {
    // search
    const search = new L.supermap.Components.Search(searchOptions);
    search.on('geocodesucceeded', function (result) {
        listen(result, searchConfig.onResultClick)
    })
    search.on('searchlayersucceeded', function(res) {
    })
    search.on('click', function(e) {

    })
    search.addTo(map)
}

function listen(result, callback) {
    let resultDomObj = document.getElementsByClassName('component-pagination__content')[0];
    resultDomObj.onclick = (e) => {
        let selectFeatureOption = null;
        if (e.target.parentNode.className === "component-search-result-info") {
            selectFeatureOption = e.target.parentNode.parentNode;
        } else if (e.target.parentNode.className === "component-search__resultitme") {
            selectFeatureOption = e.target.parentNode;
        } else if (e.target.className === "component-search__resultitme") {
            selectFeatureOption = e.target;
        } else {
            return;
        }
        let list = document.getElementsByClassName('component-search__resultitme')
        for(let i = 0;i < list.length;i++) {
            if(list[i] === selectFeatureOption) {
                if (typeof callback === 'function') callback(result[i])
            }
        }
    };
}
function getCRS(epsgCodeStr, bounds, resolutions) {
    return L.Proj.CRS(epsgCodeStr, {
        bounds: L.bounds([bounds.left, bounds.bottom], [bounds.right, bounds.top]),
        resolutions: resolutions,
        origin: [bounds.left, bounds.top],
        dpi: originResult.dpi
    });
}

function zoomIn() {
    map.zoomIn();
}

function zoomOut() {
    map.zoomOut();
}

function viewEntire() {
    var mapDiv = document.getElementById("map");
    var minSize = Math.min(parseInt(mapDiv.clientWidth), parseInt(mapDiv.clientHeight));

    var zoomLevel = Math.floor(Math.log(minSize / 256) / Math.LN2);
    map.setView(L.latLng(lat, lon), zoomLevel);
}

function showScale() {
    var scale = layer.getScale();
    scale = parseInt(1 / scale * 10) / 10;
    var scaleText = document.getElementById("scaleText");
    scaleText.value = "比例尺： 1/" + scale;
}

function showCoords() {
    var mapdiv = document.getElementById("map");
    var coordsText = document.getElementById("coordsText");
    mapdiv.onmousemove = function (e) {
        e = e || window.event;
        var point = map.mouseEventToLatLng(e);
        coordsText.value = parseFloat(point.lat).toFixed(4) + "," + parseFloat(point.lng).toFixed(4);
    }
}

function getProjectionExtent() {
    var requestUrl = url;
    requestUrl = requestUrl + "/" + "prjCoordSys/projection/extent.json";
    var commit = new Requester();
    extent = commit.sendRequestWithResponse(requestUrl, "GET", null);
    if (extent) {
        var result = eval('(' + extent + ')');
        if (result && result.left && result.right && result.top && result.bottom) {
            return result;
        }
    }
    return null;
}

function setPrjCoordSys() {// 支持动态投影，解析url相应参数
}

function scaleToResolution(scale, dpi, mapUnit) {
    var inchPerMeter = 1 / 0.0254;
    var meterPerMapUnitValue = getMeterPerMapUnit(mapUnit);
    var resolution = scale * dpi * inchPerMeter * meterPerMapUnitValue;
    resolution = 1 / resolution;
    return resolution;
}

function resolutionToScale(resolution, dpi, mapUnit) {
    var inchPerMeter = 1 / 0.0254;
    // 地球半径。
    var meterPerMapUnit = getMeterPerMapUnit(mapUnit);
    var scale = resolution * dpi * inchPerMeter * meterPerMapUnit;
    scale = 1 / scale;
    return scale;
}

function getMeterPerMapUnit(mapUnit) {
    var earchRadiusInMeters = 6378137;// 6371000;
    var meterPerMapUnit;
    if (mapUnit == "METER") {
        meterPerMapUnit = 1;
    } else if (mapUnit == "DEGREE") {
        // 每度表示多少米。
        meterPerMapUnit = Math.PI * 2 * earchRadiusInMeters / 360;
    } else if (mapUnit == "KILOMETER") {
        meterPerMapUnit = 1.0E-3;
    } else if (mapUnit == "INCH") {
        meterPerMapUnit = 1 / 2.5399999918E-2;
    } else if (mapUnit == "FOOT") {
        meterPerMapUnit = 0.3048;
    }
    return meterPerMapUnit;
}

//由于mvt的style渲染必须要传一个完整的分辨率数组，这里计算出一个从0开始的分辨率数组
function getStyleResolutions(bounds) {
    var styleResolutions = [];
    var temp = Math.abs(bounds.left - bounds.right) / 256;
    for (var i = 0; i < 22; i++) {
        if (i == 0) {
            styleResolutions[i] = temp;
            continue;
        }
        temp = temp / 2;
        styleResolutions[i] = temp;
    }
    return styleResolutions;
}

function getScales(bounds, coordUnit) {
    var resolution0 = Math.abs(bounds.left - bounds.right) / 256;
    var temp = resolutionToScale(resolution0, originResult.dpi, coordUnit);
    var scales = [];
    for (var i = 0; i < 22; i++) {
        if (i == 0) {
            scales[i] = temp;
            continue;
        }
        temp = temp * 2;
        scales[i] = temp;
    }
    return scales;
}

function Requester() {
    this.commit = null;
    try {
        this.commit = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (ex) {
        try {
            this.commit = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (ex) {
            this.commit = null;
        }
    }
    if (!this.commit && typeof XMLHttpRequest != "undefined") {
        this.commit = new XMLHttpRequest();
    }
    /**
     * 发送异步请求。
     */
    this.sendRequest = function (url, method, entry, onComplete) {
        var xhr = this.commit;
        xhr.open(method, url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        xhr.onreadystatechange = function () {
            var readyState = xhr.readyState;
            if (readyState == 4) {
                var status = xhr.status;
                var responseText = xhr.responseText;
                onComplete(responseText);

                xhr.onreadystatechange = function () { };
                xhr = null;
            }
        };
        xhr.send(entry);
    }
    /**
     * 发送一个同步请求。
     */
    this.sendRequestWithResponse = function (url, method, entry) {
        var xhr = this.commit;
        xhr.open(method, encodeURI(url), false);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        xhr.send(entry);
        return xhr.responseText;
    }
}

function getInfowindow(currentMarker) {
    return `
    <div class="info-card">
    <div class="info--title">
      <!-- <p>${ currentMarker.deviceType }</p> -->
      <p>${ currentMarker.name }</p>
    </div>
    <div class="info--content">
      <p>安装日期: ${ currentMarker.createTime }</p>
    </div>
    <div class="info--content">
      <p>地址:</p>
      <p>${ currentMarker.address }</p>
      <p>
        ${ currentMarker.longitude.toFixed(4) }
        ${ currentMarker.latitude.toFixed(4) }
      </p>
    </div>
    <div class="info--footer">
      <div>
        <img src="${iconQrcode}" alt="QID二维码" />
        <p>QID</p>
      </div>
    </div>
  </div>
    `;
}
function addMarker(marker) {
    const point = new L.Marker(marker.latlng, {
        icon: marker.type === 'green' ? greenIcon : blueIcon
    }).addTo(map);
    point.bindCustomPopup(getInfowindow(marker));

}

function registerKey(url) {
    L.supermap.SecurityManager.registerKey(url, key);
}

let featureService = null
function getFeatureService() {
    const url = 'http://23.99.215.161:8195/portalproxy/seyu25r6/iserver/services/data-yzqwlsb/rest/data';
    registerKey(url)
    if (featureService === null) {
        featureService = new L.supermap
        .FeatureService(url)
    }
    return featureService
}

// https://23.99.215.141:21104/portalproxy/5kj677e0/iserver/services/data-poi/rest
function getIcon() {
    return blueIcon
}
let processingService = null
function getProcessingService() {
    const url = 'http://23.99.215.161:8195/portalproxy/seyu25r6/iserver/services/data-yzqwlsb/rest/data';
    new L.supermap.ProcessingService(url, {
        withCredentials: window.isLocal
    });
}

let poiService = null
function searchPOI(name) {
    const url = 'http://23.99.215.161:8195/portalproxy/5kj677e0/iserver/services/data-poi/rest/data';
    registerKey(url)
    if (poiService === null) {
        registerKey(url)
        poiService = new L.supermap
        .FeatureService(url)

    }
    var sqlParam = new L.supermap.GetFeaturesBySQLParameters({
        queryParameter: {
            attributeFilter: `NAME like '%${name}%'`
        },
        datasetNames: ["poi:poi"]
    });
    return new Promise((resolve, reject) => {
        poiService.getFeaturesBySQL(sqlParam, function (serviceResult) {
            resolve(serviceResult);
            // resultLayer = L.geoJSON(serviceResult.result.features).addTo(map).bindPopup('SMID = 234');
        });
    }).catch(() => {})
}
export default {
    init,
    map,
    addMarker,
    registerKey,
    getFeatureService,
    getIcon,
    getProcessingService,
    getInfowindow,
    searchPOI
}
